package com.chenyue.cm.base.config;

import com.chenyue.cm.auth.AuthorizationInterceptor;
import com.chenyue.cm.auth.LoginUserHandlerMethodArgumentResolver;
import com.chenyue.cm.decrypt.ParamDecodeResolver;
import com.chenyue.cm.decrypt.ParamEncodeResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author Administrator
 * Spring 5.0后，WebMvcConfigurerAdapter被废弃，取代的方法有两种：
 * ①implements WebMvcConfigurer（官方推荐）
 * ②extends WebMvcConfigurationSupport
 * 使用第一种方法是实现了一个接口，可以任意实现里面的方法，不会影响到Spring Boot自身的@EnableAutoConfiguration，
 * 而使用第二种方法相当于覆盖了@EnableAutoConfiguration里的所有方法，每个方法都需要重写，
 * 比如，若不实现方法addResourceHandlers()，则会导致静态资源无法访问
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final AuthorizationInterceptor authorizationInterceptor;

    private final LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

    private final ParamDecodeResolver paramDecodeResolver;

    private final ParamEncodeResolver paramEncodeResolver;

    @Value("${lcmaster.upload.systemUploadPath}")
    private String systemUploadPath;

    @Value("${lcmaster.upload.kindeditorUploadPath}")
    private String kindeditorUploadPath;

    public WebMvcConfig(AuthorizationInterceptor authorizationInterceptor, LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver, ParamDecodeResolver paramDecodeResolver, ParamEncodeResolver paramEncodeResolver) {
        this.authorizationInterceptor = authorizationInterceptor;
        this.loginUserHandlerMethodArgumentResolver = loginUserHandlerMethodArgumentResolver;
        this.paramDecodeResolver = paramDecodeResolver;
        this.paramEncodeResolver = paramEncodeResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //上传文件路径
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + systemUploadPath);
        registry.addResourceHandler("/uploads/**").addResourceLocations("file:" + kindeditorUploadPath);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**");
        registry.addInterceptor(paramDecodeResolver)
                .addPathPatterns("/api/**");
        registry.addInterceptor(paramEncodeResolver)
                .addPathPatterns("/api/**");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
    }

}